#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <err.h>
#include <libmscommon/mscommon.h>
#include <libmscommon/msepoll.h>
#include <libmscommon/msstring.h>
#include <libmscommon/mstime.h>
#include <libmslog/mslog.h>
#include <libmsprotocol/msprotocol.h>

#define FLAG "SRTCLIENT_SAMPLE"

int main(int argc, char **argv)
{
	mslog_api_init( 53, ms_null,ms_null, ms_null);
	if(3!=argc){
		ms_error("usage:%s   inurl(udp|srt)   outurl(srt|udp)",argv[0]);
		ms_error("	push		srt://127.0.0.1:8100?streamid=msos.push/live/123");
		ms_error("	pull		srt://127.0.0.1:8100?streamid=msos.pull/live/123");
		mslog_api_deinit();
		return -1;
	}
	msptc_api_init();
	msptc_api_register();
	//srt_setloglevel(4);
	URLContext urlctt_in;
	URLContext urlctt_out;
	ms_memset(&urlctt_in,0,sizeof(URLContext));
	ms_memset(&urlctt_out,0,sizeof(URLContext));
	ms_strcpy(urlctt_in.url, argv[1]);
	ms_strcpy(urlctt_out.url, argv[2]);
	msptc_api_urlSplit_urlctt(&urlctt_in);
	msptc_api_urlSplit_urlctt(&urlctt_out);
	
	URLProtocol *msptl_in=msptc_api_matchByName(urlctt_in.url_info.ptcName);
	URLProtocol *msptl_out=msptc_api_matchByName(urlctt_out.url_info.ptcName);

	urlctt_in.opt.udp.ifcIn="lo";
	urlctt_in.opt.udp.ipIn="192.168.200.83";
	if(msptl_in->url_open(&urlctt_in)<0){
		ms_errExit(-1, "Open in url failed");
	}
	
	urlctt_out.flags|=FLAG_WRITE;
	if(msptl_out->url_open(&urlctt_out)<0){
		ms_errExit(-1, "Open out url failed");
	}
	char buf[2048]={0};
	int len=0;
	time_t EtimepInstant;
	time_t EtimepGL;
	int fd=0;
	ms_bool flag_srtSender=ms_true;
	if(ms_strncmp_saeq(urlctt_in.url_info.ptcName, PTLNAME_SRT)){
		fd=urlctt_in.fd;
		flag_srtSender=ms_false;
	}else{
		fd=urlctt_out.fd;
		flag_srtSender=ms_true;
	}
	while(1){
		len=msptl_in->url_read(&urlctt_in,buf,2048);
		if(len>0){
			if(msptl_out->url_write(&urlctt_out,buf,len)<0){
				mssrt_bstatsGL(fd, flag_srtSender);
				ms_error("url_write error");
				break;
			}
		}else{
			ms_error("recv error,len=%d", len);
			//break;
		}
		ms_usleep(500);
		if(mstime_api_counterAsyncSec(&EtimepInstant, 10)){
			//mssrt_bstatsInstant(fd, flag_srtSender);
		}
		if(mstime_api_counterAsyncSec(&EtimepGL, 60)){
			//mssrt_bstatsGL(fd, flag_srtSender);
		}
	}	
	msptl_in->url_close(&urlctt_in);
	msptl_out->url_close(&urlctt_out);
	msptc_api_deinit();
	mslog_api_deinit();
}
#undef MAIN_C

